#!/bin/bash

remoteAddr="http://192.168.56.104:9494/"

curl -s ${remoteAddr}"getConfig" > /tmp/check_mount.txt

list=`cat /tmp/check_mount.txt | sed "s/.*\"local\":\"\([^\"]*\)\".*/\1/g"`
netpath=`cat /tmp/check_mount.txt | sed "s/.*\"network\":\"\([^\"]*\)\".*/\1/g"`
user=`cat /tmp/check_mount.txt | sed "s/.*\"username\":\"\([^\"]*\)\".*/\1/g"`
passwd=`cat /tmp/check_mount.txt | sed "s/.*\"password\":\"\([^\"]*\)\".*/\1/g"`

result=''
output=''

callback(){
  curl -X POST -H "'Content-type':'application/json'" -d $1 ${remoteAddr}"monitor" > /dev/null 2>&1
  exit 0
}

if [ -z $list ]
then
  callback '{"output":"远程数据为空"}'
fi

listArr=(${list//,/ })
netpathArr=(${netpath//,/ })
userArr=(${user//,/ })
passwdArr=(${passwd//,/ })

startTime_s=`date +%s`

#curl -i -X POST -H "'Content-type':'application/json'" -d '{"ATime":"'$atime'","BTime":"'$btime'"}' $url
check_mount(){
  ls $1 > /dev/null 2>&1
  if [ $? != 0 ]
  then
    return 1
  else
    mount | grep $1 > /dev/null
    if [ $? != 0 ]
    then
      return 1
    fi
  fi
  return 0
}

run_mount(){
  mount | grep $1 > /dev/null
  if [ $? == 0 ]
  then
    umount $1
  fi
  #case $1 in
  #/root/share)
  #  mount -t cifs -o username="administrator",password=111111 //192.168.56.104/share /root/share
  #  ;;
  #/root/test_share2)
  #  mount -t cifs -o username="administrator",password=111111 //192.168.56.104/test_share /root/test_share2
  #  ;;
  #esac
  mount -t cifs -o username=$3,password=$4 $2 $1 > /tmp/check_mount_error 2>&1
  return $?
}

case $1 in
stop)
  for((i = 0;i<${#listArr[@]};i++)) do
      umount ${listArr[i]}
  done
  exit 0
  ;;
start)
  for((i = 0;i<${#listArr[@]};i++)) do
    check_mount ${listArr[i]}
    if [ $? != 0 ]
    then
        run_mount ${listArr[i]} ${netpathArr[i]} ${userArr[i]} ${passwdArr[i]}
        if [ $? == 0 ]
        then
          result=${result}'"'${listArr[i]}'":"success",'
        else
          result=${result}'"'${listArr[i]}'":"failure('`cat /tmp/check_mount_error`')",'
        fi
    else
      result=${result}'"'${listArr[i]}'":"normal",'
    fi
  done
  ;;
*)
  echo $0 "(start|stop)"
  ;;
esac
endTime_s=`date +%s`
seconds=$[ $endTime_s - $startTime_s ]
result=${result}'"output":"耗时：'${seconds}'s"'
callback '{'${result}'}'